<template>
  <div ref="chartRef" class="echarts-container"></div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick } from 'vue';
import * as echarts from 'echarts';

const props = defineProps({
  option: {
    type: Object,
    required: true
  },
  width: {
    type: String,
    default: '100%'
  },
  height: {
    type: String,
    default: '100%'
  }
});

const chartRef = ref(null);
let chartInstance = null;

// 初始化图表
const initChart = () => {
    debugger
  if (!chartRef.value) return;
  
  // 销毁已存在的实例
  if (chartInstance) {
    chartInstance.dispose();
    chartInstance = null;
  }
  
  // 创建新实例
  chartInstance = echarts.init(chartRef.value);
  
  // 设置图表配置
  if (props.option) {
    chartInstance.setOption(props.option);
  }
  
  // 监听窗口大小变化，调整图表
  window.addEventListener('resize', handleResize);
};

// 处理窗口大小变化
const handleResize = () => {
  if (chartInstance) {
    chartInstance.resize();
  }
};

// 生命周期钩子
onMounted(() => {
  nextTick(() => {
    initChart();
  });
});

onUnmounted(() => {
  if (chartInstance) {
    chartInstance.dispose();
    chartInstance = null;
  }
  window.removeEventListener('resize', handleResize);
});

// 监听props变化，更新图表
watch(() => props.option, (newOptions) => {
  if (chartInstance && newOptions) {
    chartInstance.setOption(newOptions);
  }
}, { deep: true });
</script>

<style scoped>
.echarts-container {
  width: 100%;
  height: 100%;
}
</style>